import axios from 'axios'

const url = 'tpp5'

// type
const ERROR_MSG = 'ERROR_MSG'
const LOGIN = 'LOGIN'
const LOGOUT = 'LOGOUT'
const GET_CODE = 'GET_CODE'

// 初始状态
const initState = {
    msg:''
}

// reducer

export function loginAndReg(state=initState,action) {
    switch(action.type) {
        // case "LOGIN":
        // case "LOGOUT":
        case "ERROR_MSG": 
            return {...state,msg:action.msg}
        case "GET_CODE":
            return {data:action.data}
        default:
            return state
    }
}

// action

function errMsg(msg) {
    return {
        msg,
        type:'ERROR_MSG'
    }
}
function Code(data) {
    return {
        type: GET_CODE,
        data
    }
}





export function login({user,pwd}) {
    if(!user || !pwd) {
        return errMsg('用户名密码必须输入')
    }
    // return dispatch => {
    //     axios.post('/',{user,pwd}).then(res => {
    //         if(res.status === 200) {
    //             dispatch(authSuccess(res.data.data))
    //         }else {
                
    //         }
    //     })
    // }
}


export function getCode() {
    return dispatch => {
        axios.get(`/${url}/getCode`).then(res => {
            console.log('获取验证码',res)
            if(res.status === 200) {
                dispatch(Code(res.data))
            }else {
                console.log('错误')
            }
        })
    }
}


export function register({username,password,repeatpwd,verification,verification_user,sex,age,birthday,site,mailbox}) {
    if(!username || !password) {
        return errMsg('用户名密码必须输入')
    }
    if(password !== repeatpwd) {
        return errMsg('密码不一致')
    }if(verification != verification_user) {
        return errMsg('验证码输入有误，请重新输入')
    }
    return dispatch => {
        axios.post(`/${url}/addUser`,{username,password,sex,age,birthdayString:birthday,site,mailbox,verification})
        .then(res => {
            console.log('请求成功',res)

            // if(res.status === 200) {
            //     dispatch(authSuccess(res.data.data))
            // }else {
                
            // }
        })
    }
}